package agent

import (
	"context"
	"github.com/kataras/golog"
	"nprobe/core"
	"nprobe/core/aggregate"
)

type Agent interface {
	GetName() string
	StartAgent() error
	StopAgent() error
}

type BaseAgent struct {
	Name          string
	Task          *core.ProbeTask
	SenderGroup   *core.SenderGroup
	ReceiverGroup *core.ReceiverGroup
	Aggregator    aggregate.Aggregator

	Ctx        context.Context
	CancelFunc context.CancelFunc
}

func (b *BaseAgent) GetName() string {
	return b.Name
}

func (b *BaseAgent) StartAgent() error {

	err := b.Aggregator.StartAggregator()
	if err != nil {
		golog.Infof("start aggregator failed. err: %+v", err)
		return err
	}

	err = b.ReceiverGroup.StartReceiverGroup()
	if err != nil {
		golog.Infof("start receiver group failed. err: %+v", err)
		return err
	}

	if b.SenderGroup != nil {
		err = b.SenderGroup.StartSenderGroup()
		if err != nil {
			golog.Infof("start sender group failed. err: %+v", err)
			return err
		}
	}

	return nil
}

func (b *BaseAgent) StopAgent() error {
	if b != nil {
		if b.CancelFunc != nil {
			b.CancelFunc()
		}
	}

	return nil
}
